//
//  ListViewController.m
//  ACSProduct
//
//  Created by gaurav on 09/10/11.
//  Copyright 2011 dhillon. All rights reserved.
//

/*
 PUB   PUBS NULL 1
 DISC  DISCO NULL 1
 MONU  MONUMENT NULL 1
 ART   ART & CULTURE NULL 1
 */

/*
 Address = "Dining02 Address 1, Burton on trent";
 Deal = Dining02;
 DealBanner = "Dining02 Tag Line";
 DealDesc = "Dining02 Promo Description";
 DealIcon = 3;
 DealId = 101;
 DealImage1 = "VenueImages/Dining02DealImage01.png";
 DealImage2 = "VenueImages/Dining02DealImage02.png";
 DealImage3 = "VenueImages/Dining02DealImage03.png";
 DealImageHow = "VenueImages/no_image.jpg";
 DealUpdated = "2012-10-02T17:00:00";
 Desc = "Dining02 Description";
 Email = "info@Dining02.co.uk";
 Image1 = "VenueImages/Dining02VenueImage01.png";
 Image2 = "VenueImages/Dining02VenueImage02.png";
 Image3 = "VenueImages/Dining02VenueImage03.png";
 Lat = "52.8077920";
 Long = "-1.6471350";
 Name = Dining02;
 OperatingHrs = "9am-5pm";
 Phone = 1283000002;
 PostCode = DE13002;
 Type = DINI;
 URL = "www.Dining02.co.uk";
 VenueLogoImage = "VenueImages/Dining02Logo.png";
 
 
 <Lists><List><ListType>Cat</ListType><Type>PUBS </Type><Name>PUBS1</Name><Lat>52.7898100</Lat><Long>-1.5654210</Long><Address>26 Aston Drive, Newhall</Address><Email>Paul.cantrill@acs-ltd.uk.com</Email><Phone>7958548890</Phone><URL>www.acs-ltd.uk.com</URL><Cost>100</Cost><Desc>Where it all happens, the centre of the universe.</Desc><Deal>Offer</Deal><DealDesc>Promotional Offer</DealDesc><DealExpires>2011-11-11T00:00:00</DealExpires><Miles>5.248484479945753e+003</Miles><Image></Image></List>
 
 <ListType>Cat</ListType><Name>PUBS2</Name><Long>-1.5654210</Long><Email>Paul.cantrill@acs-ltd.uk.com</Email><URL>www.acs-ltd.uk.com</URL><Desc>Where it all happens, the centre of the universe.</Desc><DealDesc>Promotional Offer</DealDesc><Miles>5.248484479945753e+003</Miles>
 
 <List><ListType>Cat</ListType><Type>PUBS </Type><Name>PUBS3</Name><Lat>52.7898100</Lat><Long>-1.5654210</Long><Address>26 Aston Drive, Newhall</Address><Email>Paul.cantrill@acs-ltd.uk.com</Email><Phone>7958548890</Phone><URL>www.acs-ltd.uk.com</URL><Cost>100</Cost><Desc>Where it all happens, the centre of the universe.</Desc><Deal>Offer</Deal><DealDesc>Promotional Offer</DealDesc><DealExpires>2011-11-11T00:00:00</DealExpires><Miles>5.248484479945753e+003</Miles><Image></Image></List>
 
 
 
 
 <ListType>Cat</ListType><Name>PUBS4</Name><Long>-1.5654210</Long><Email>Paul.cantrill@acs-ltd.uk.com</Email><URL>www.acs-ltd.uk.com</URL><Desc>Where it all happens, the centre of the universe.</Desc><DealDesc>Promotional Offer</DealDesc><Miles>5.248484479945753e+003</Miles>
 
 <List><ListType>Cat</ListType><Type>PUBS </Type><Name>PUBS5</Name><Lat>52.7898100</Lat><Long>-1.5654210</Long><Address>26 Aston Drive, Newhall</Address><Email>Paul.cantrill@acs-ltd.uk.com</Email><Phone>7958548890</Phone><URL>www.acs-ltd.uk.com</URL><Cost>100</Cost><Desc>Where it all happens, the centre of the universe.</Desc><Deal>Offer</Deal><DealDesc>Promotional Offer</DealDesc><DealExpires>2011-11-11T00:00:00</DealExpires><Miles>5.248484479945753e+003</Miles><Image></Image></List>
 
 </Lists>
 */
#import "ListViewController.h"


@implementation ListViewController
@synthesize arrayList,stringTitle,stringSub,stringCatInd,isFromHome,downloads,urls,stringCat,scrllSubCat;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void) didFinishDownload:(NSNumber*)idx
{
    //for(int i=0;i<[arrayImages count];i++)
    //{
    
    UIImageView *viewImage = [arrayImages objectAtIndex:[idx intValue]];
    viewImage.image = [UIImage imageWithData:[downloads dataAtIndex:[idx intValue]]];
    
    //}
    //    if([idx intValue]==0)
    //    {
    //    
    //        imageV1.image = [UIImage imageWithData:[downloads dataAtIndex:[idx intValue]]];
    //
    //    }
    //    if([idx intValue]==1)
    //    {
    //        
    //        imageV2.image = [UIImage imageWithData:[downloads dataAtIndex:[idx intValue]]];
    //        
    //    }
    //[arrayAlbums addObject:[[[downloads dataAsStringAtIndex: [idx intValue]] JSONValue]copy]];
	//NSLog(@"%d download: %@", [idx intValue], [downloads dataAsStringAtIndex: [idx intValue]]);
    
}

- (void) didFinishAllDownload {
    [tableList reloadData];
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}
-(void)reloadData:(NSNotificationCenter*)notification
{
    [tableList   reloadData];
}
#pragma mark - View lifecycle
- (void)viewWillAppear:(BOOL)animated
{
//    [[NSNotificationCenter  defaultCenter] addObserver:self
//                                              selector:@selector(datareload:) 
//                                                  name:KsReLOADDATAMETERRAN
//                                                object:nil];
//    
//    [[NSNotificationCenter  defaultCenter] addObserver:self
//                                              selector:@selector(datareload:) 
//                                                  name:KsReLOADDATAPlace
//                                                object:nil];
//    
//    [[NSNotificationCenter  defaultCenter] addObserver:self
//                                              selector:@selector(datareload:) 
//                                                  name:KsReLOADDATAZipCode
//                                                object:nil];
//    if(kmsel == 0 && KMselect != 0)
//    {
//        [tableList reloadData];
//        kmsel = 1;
//    }
//    else if(kmsel == 1 && KMselect !=1 )
//    {
//        [tableList reloadData];
//        kmsel = 0;
//    }
}

-(void)sort
{
    if(isSortDate == 1)
    {
        isSortDate = 0;
        [self.navigationItem  setRightBarButtonItem:[[UIBarButtonItem  alloc] initWithTitle:@"By Distance" style:UIBarButtonItemStyleDone target:self action:@selector(sort)]];
   
    }
    else
    {
        isSortDate = 1;
        [self.navigationItem  setRightBarButtonItem:[[UIBarButtonItem  alloc] initWithTitle:@"By Deal Updated" style:UIBarButtonItemStyleDone target:self action:@selector(sort)]];
    }
    
//    [self  sortTheArray];
    [tableList  reloadData];
}


-(void)sortTheArray
{
    if(isSortDate == 1)
    {
        //Distance
//        NSSortDescriptor *nameSort = [NSSortDescriptor sortDescriptorWithKey:@"DealUpdated" ascending:YES];
//        NSArray *sortDescriptors = [NSArray arrayWithObject:nameSort];
//        
//        arrayList = [NSMutableArray  arrayWithArray:[arrayList sortedArrayUsingDescriptors:sortDescriptors]];

//        scores = [NSMutableArray arrayWithArray:[defaults bjectForKey:@"HighScores"]];
        NSSortDescriptor *myDescriptor; //= [[NSSortDescriptor alloc] initWithKey:kRadius ascending:YES];
        myDescriptor =[NSSortDescriptor sortDescriptorWithKey:@"DealUpdated"
                                                    ascending:YES
                                                     selector:@selector(localizedStandardCompare:)];
        [arrayList sortUsingDescriptors:[NSArray arrayWithObject:myDescriptor]];
        
//        NSSortDescriptor *sorter = [[[NSSortDescriptor alloc]
//                                     initWithKey:@"DealUpdated"
//                                     ascending:YES
//                                     selector:@selector(localizedCaseInsensitiveCompare:)] autorelease];
//        NSArray *sortDescriptors = [NSArray arrayWithObject: sorter];
//        [arrayList sortUsingDescriptors:sortDescriptors];
    }
    else{
//        NSSortDescriptor *nameSort = [NSSortDescriptor sortDescriptorWithKey:@"Distance" ascending:YES];
//        NSArray *sortDescriptors = [NSArray arrayWithObject:nameSort];
//        
//        arrayList = [NSMutableArray  arrayWithArray:[arrayList sortedArrayUsingDescriptors:sortDescriptors]];
        NSSortDescriptor *myDescriptor; //= [[NSSortDescriptor alloc] initWithKey:kRadius ascending:YES];
        myDescriptor =[NSSortDescriptor sortDescriptorWithKey:@"Distance"
                                                    ascending:YES
                                                     selector:@selector(localizedStandardCompare:)];
        [arrayList sortUsingDescriptors:[NSArray arrayWithObject:myDescriptor]];
    }
    
}

- (void)viewDidLoad
{
    isSortDate = 0;
    
//    [[NSNotificationCenter  defaultCenter] addObserver:self
//                                              selector:@selector(datareload:) 
//                                                  name:KsReLOADDATAMETERRAN
//                                                object:nil];
//    
//    [[NSNotificationCenter  defaultCenter] addObserver:self
//                                              selector:@selector(datareload:) 
//                                                  name:KsReLOADDATAPlace
//                                                object:nil];
//    
//    [[NSNotificationCenter  defaultCenter] addObserver:self
//                                              selector:@selector(datareload:) 
//                                                  name:KsReLOADDATAZipCode
//                                                object:nil];
    
    [self.navigationItem  setRightBarButtonItem:[[UIBarButtonItem  alloc] initWithTitle:@"By Distance" style:UIBarButtonItemStyleDone target:self action:@selector(sort)]];
    
    tableList.backgroundView = nil;
    tableList.backgroundColor = [UIColor  clearColor];
    
    
    if (_refreshHeaderView == nil)
    {
		EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - tableList.bounds.size.height, self.view.frame.size.width, tableList.bounds.size.height)];
        view.backgroundColor = [UIColor clearColor];
		view.delegate = self;
		[tableList addSubview:view];
		_refreshHeaderView = view;
		[view release];
	}
    
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadData:) name:CHANGEMEASUNIT object:nil];
    
    NSMutableArray *arraySub;
    
    
    if([self.stringTitle isEqualToString:@"Dining"])
        arraySub = [[NSMutableArray alloc] initWithObjects:KsDINNING];
    
    else if([self.stringTitle isEqualToString:@"Nightlife"])
        arraySub = [[NSMutableArray alloc] initWithObjects:KsNIGHTLIFE];
    
    else if([self.stringTitle isEqualToString:@"Beauty and Spa"])
        arraySub = [[NSMutableArray alloc] initWithObjects:KsBEATSPA];
    
    else if([self.stringTitle isEqualToString:@"Shopping"])
        arraySub = [[NSMutableArray alloc] initWithObjects:KsSHOPPING];
    
    else if([self.stringTitle isEqualToString:@"Arts and Entertainment"])
        arraySub = [[NSMutableArray alloc] initWithObjects:KsARTSANDENTER];
    
    else if([self.stringTitle isEqualToString:@"Health and Fitness"])
        arraySub = [[NSMutableArray alloc] initWithObjects:KsHealthFitness];
    
    else if([self.stringTitle isEqualToString:@"Accomodation"])
        arraySub = [[NSMutableArray alloc] initWithObjects:KsAccomodation];
    
    else if([self.stringTitle isEqualToString:@"Services"])
        arraySub = [[NSMutableArray alloc] initWithObjects:KsService];
    
    else if([self.stringTitle isEqualToString:@"Travel"])
        arraySub = [[NSMutableArray alloc] initWithObjects:KsTravel];
    
    else if([self.stringTitle isEqualToString:@"Pubs"])
        arraySub = [[NSMutableArray alloc] initWithObjects:KsPubs];
    
    else if([self.stringTitle isEqualToString:@"Florists"])
        arraySub = [[NSMutableArray alloc] initWithObjects:KsFlorists];
    
    else if([self.stringTitle isEqualToString:@"Clubs and Groups"])
        arraySub = [[NSMutableArray alloc] initWithObjects:KsClubsandGroups];
    
     //[scrllSubCat setButtons:arraySub];
    
    scrllSubCat.delegatePress = self;
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor] ];
    
    //    if(self.isFromHome != 1)
    //    {
    //        self.stringTitle = TITTLELIST;
    //        arrayList = [[NSMutableArray alloc] initWithArray:arrayAllData];
    //    }
    //    
    
    
    [self.navigationItem setTitle:stringTitle];
    
    //    self.urls = [[NSMutableArray alloc]init];
    //    arrayImages = [[NSMutableArray alloc] init];
    //    for(int i=0;i<[arrayList count];i++)
    //    {
    //        UIImageView *imageViewList = [[UIImageView alloc] initWithFrame:CGRectMake(0,
    //                                                                                   1,
    //                                                                                   55,
    //                                                                                   43)];
    //        [arrayImages addObject:imageViewList];
    //         [self.urls addObject:[[[[arrayList objectAtIndex:i]objectForKey:FIELDIMAGES]objectForKey:FIELDIMAGE]objectAtIndex:0]];
    //    }
    //    
    
    //    self.downloads = [[MultipleDownload alloc] initWithUrls: urls];
    //    self.downloads.delegate = self;
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view
                                              animated:YES];
    hud.labelText = @"Loading...";
    
    isDataForScrlView = YES;
    
    [self dataFromServer];
    
    UIButton *btnBack=[UIButton buttonWithType:UIButtonTypeCustom];
    [btnBack setFrame:CGRectMake(0, 10, 50, 30)];
    [btnBack setImage:[UIImage imageNamed:@"Back.png"] forState:UIControlStateNormal];
    [btnBack addTarget:self
                action:@selector(clickToBackBtn:)
      forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:btnBack];
   
    
    [super viewDidLoad];
    
    // Do any additional setup after loading the view from its nib.
}

-(void)datareload:(NSNotification *)notificaton
{
    [self dataFromServer];
}


#pragma mark -viewDidAppear-

-(void)viewDidAppear:(BOOL)animated
{
    
}


#pragma mark -clickToBackBtn-

-(IBAction)clickToBackBtn:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark -dataFromServer-

-(void)dataFromServer
{
    NSLog(@"isDataForScrlView=%d",isDataForScrlView);
    ASIFormDataRequest *request;
    if(isDataForScrlView == YES)
    {
        request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:URLDATANEW]];
        [request setRequestMethod:@"POST"];
        [request setPostValue:stringCat forKey:BASECAT];
        [request setDelegate:self];
    }
    else
    {
        request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:URLDATA]];
        
        //        if(![ModalController  getContforKey:sPhoneLocation])
        //            radius = [[ModalController  getContforKey:sPhoneLocation] integerValue];
        //        else 
        //        {
        //            radius = 20000;
        //        }
        
        BOOL isAnySwitchOn = 0;
        
        
//        else 
//        {
//            [request setPostValue:locationUser.strUserLat forKey:BASELAT];
//            [request setPostValue:locationUser.strUserLong forKey:BASELONG];
//            radius = 20000;
//        }
        if(TESTMODE)
            radius = 20000;
        [request setRequestMethod:@"POST"];
//        [request setPostValue:@"" forKey:kSubCatId];
//        [request setPostValue:@"" forKey:BASEIND];
//        [request setPostValue:@"" forKey:BASECAT];
        
        
        
        [request setPostValue:stringCatInd forKey:BASEIND];
        [request setPostValue:stringCat forKey:BASECAT];
        
        if([[[arraySubCat objectAtIndex:subCatIndex] objectForKey:kSubCatId] isEqualToString:@"All"])
            [request setPostValue:@"" forKey:kSubCatId];
        else
            [request setPostValue:[[arraySubCat objectAtIndex:subCatIndex] objectForKey:kSubCatId]  forKey:kSubCatId];
        
        
        if([ModalController  getContforKey:KsSWITCHEDMETER] )
        {
            //[request setPostValue:@"999999"  forKey:@"City"];
            [request setPostValue:locationUser.strUserLat forKey:BASELAT];
            [request setPostValue:locationUser.strUserLong forKey:BASELONG];
            
            isAnySwitchOn = 1;
            radius =[[ModalController getContforKey:sPhoneLocation] integerValue];
            [request setPostValue:[NSString stringWithFormat:@"%d",radius] forKey:BASEDIS];
        }
        
        if([ModalController getContforKey:KsSWITCHEDPOSTCODE])
        {
            isAnySwitchOn = 1;
            //[request setPostValue:@"999999"  forKey:@"City"];

            [request setPostValue:[ModalController getContforKey:sPostCode]  forKey:@"PostCode"];
        }
        
        if([ModalController getContforKey:ksSWITCHEDHOME])
        {
            isAnySwitchOn = 1;
            //[request setPostValue:@"999999"  forKey:@"City"];

            [request setPostValue:[ModalController getContforKey:sHome]  forKey:@"PostCodeHome"];
        }
        
        if([ModalController getContforKey:ksSWITCHEDPLACE])
        {
            isAnySwitchOn = 1;
            [request setPostValue:[ModalController getContforKey:sPlace]  forKey:@"City"];
        }
        
        if(isAnySwitchOn == 0)
        {
            radius = 20000;
            [request setPostValue:locationUser.strUserLat forKey:BASELAT];
            [request setPostValue:locationUser.strUserLong forKey:BASELONG];
            [request setPostValue:[NSString stringWithFormat:@"%d",radius] forKey:BASEDIS];
        }
        
        
        [request setDelegate:self];
        
        NSLog(@"[ModalController getContforKey:sPostCode]---%@",[ModalController getContforKey:sPostCode]);
        NSLog(@"[ModalController getContforKey:sHome]---%@",[ModalController getContforKey:sPlace]);
        NSLog(@"%d",radius);
        NSLog(@"stringCat~~~~~~~%@",stringCat);
        NSLog(@"locationUser.strUserLat~~~~~~%@",locationUser.strUserLat);
        NSLog(@"locationUser.strUserLong~~~~~~%@",locationUser.strUserLong);
        NSLog(@"stringCatInd~~~~~~%@",stringCatInd);
        NSLog(@"subCatIndex~~~~~~~ >>>>> %@",[[arraySubCat objectAtIndex:subCatIndex] objectForKey:kSubCatId]);
        if(LOGOFF == 1)
            NSLog(@"request List = %@",request);
    }
    [request startAsynchronous];
    
    
}

#pragma mark -requestFinished-

- (void)requestFinished:(ASIHTTPRequest *)request
{
    [self doneLoadingTableViewData];
    
    [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
    
    NSLog(@"I have got data------->>>>>%@",[request responseString]);
    
    NSError *err;
    NSDictionary *_xmlDictionaryData = [XMLReader dictionaryForXMLData:[request responseData] 
                                                                 error:&err];
    if(isDataForScrlView == YES)
    {
        isDataForScrlView=NO;
        if([[_xmlDictionaryData objectForKey:kSubCategories] objectForKey:kSubCategory])
        {
            NSMutableDictionary *dictTemp=[[NSMutableDictionary alloc]init];
            [dictTemp setValue:@"All" forKey:kCatId];
            [dictTemp setValue:@"All" forKey:kSubCatDesc];
            [dictTemp setValue:@"All" forKey:kSubCatId];
            
            arraySubCat = [[NSMutableArray alloc] init];
            [arraySubCat addObject:dictTemp];

            if([[[_xmlDictionaryData objectForKey:kSubCategories] objectForKey:kSubCategory] isKindOfClass:[NSArray class]])
                [arraySubCat addObjectsFromArray:[[_xmlDictionaryData objectForKey:kSubCategories] objectForKey:kSubCategory]];
            else
                [arrayList addObject:[[_xmlDictionaryData objectForKey:kSubCategories] objectForKey:kSubCategory]];
            
            
            
            // NSLog(@"arraySubCat = %@",arraySubCat);
            
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            hud.labelText = @"Loading...";
            
            NSSortDescriptor *myDescriptor; //= [[NSSortDescriptor alloc] initWithKey:kRadius ascending:YES];
            myDescriptor =[NSSortDescriptor sortDescriptorWithKey:kSubCatDesc ascending:YES selector:@selector(localizedStandardCompare:)];
            [arraySubCat sortUsingDescriptors:[NSArray arrayWithObject:myDescriptor]];
            
            [scrllSubCat setButtons:arraySubCat];
            subCatIndex = 0;
            
            [NSTimer scheduledTimerWithTimeInterval:0.0 target:self selector:@selector(dataFromServer) userInfo:nil repeats:NO];
        }
        else
        {
            NSMutableDictionary *dictTemp=[[NSMutableDictionary alloc]init];
            [dictTemp setValue:@"All" forKey:kCatId];
            [dictTemp setValue:@"All" forKey:kSubCatDesc];
            [dictTemp setValue:@"All" forKey:kSubCatId];
            arraySubCat = [[NSMutableArray alloc] init];
            [arraySubCat addObject:dictTemp];
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            hud.labelText = @"Loading...";
            [scrllSubCat setButtons:arraySubCat];
            subCatIndex = 0;
            [NSTimer scheduledTimerWithTimeInterval:0.0 target:self selector:@selector(dataFromServer) userInfo:nil repeats:NO];
        }
    }
    else
    {
        if([[_xmlDictionaryData objectForKey:@"Lists"] objectForKey:@"List"])
        {
            if([[[_xmlDictionaryData objectForKey:@"Lists"] objectForKey:@"List"] isKindOfClass:[NSArray class]])
                arrayList  = [[NSMutableArray alloc] initWithArray:[[_xmlDictionaryData objectForKey:@"Lists"] objectForKey:@"List"]];
            
            else
            {
                arrayList = [[NSMutableArray alloc] init];
                [arrayList addObject:[[_xmlDictionaryData objectForKey:@"Lists"] objectForKey:@"List"]];
            }
            
//            for(int i=0;i<[arrayList  count];i++)
//            {
//                NSMutableDictionary *dict = [NSMutableDictionary  dictionaryWithDictionary:[arrayList  objectAtIndex:i]];
//                [dict setObject:[ModalController  calDistancebetWithLat:[locationUser.strUserLat doubleValue] with:[locationUser.strUserLong doubleValue] with:[[[arraySelect objectAtIndex:i ]objectForKey:@"Lat"]doubleValue] with:[[[arraySelect objectAtIndex:i ]objectForKey:@"Long"]doubleValue]] forKey:@"Distance"];
//                [arrayList  replaceObjectAtIndex:i withObject:dict];
//            }
        }
        else
        {
            [arrayList removeAllObjects];
            [ModalController showTheAlertWithMsg:[NSString stringWithFormat:@"No Venue Found Within Selected Search Criteria"]
                                       withTitle:@"Info"
                                    inController:self];
        }
        NSLog(@"%@",arrayList);
        
        //        for(int i=0;i<31;i++)
        //        {
        //            NSMutableDictionary *dictTemp=[[NSMutableDictionary alloc]init];
        //            [dictTemp setValue:@"All" forKey:kCatId];
        //            [dictTemp setValue:@"All" forKey:kSubCatDesc];
        //            [dictTemp setValue:@"All" forKey:kSubCatId];
        //            [arrayList addObject:dictTemp];
        //        }
        [self assignInitialValue];
        
//        [self  sortTheArray];
        
        [tableList reloadData];
    }
}


#pragma mark -requestFailed-

- (void)requestFailed:(ASIHTTPRequest *)request
{
    [self doneLoadingTableViewData];
    
    [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
    
    [ModalController showTheAlertWithMsg:@"Error in network" withTitle:@"Failed" inController:self];        
}


#pragma mark -selectSubCat-

-(void)selectSubCat:(NSInteger)index
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    hud.labelText = @"Loading...";

    subCatIndex = index;
    [self dataFromServer];
}

#pragma mark -
#pragma mark - UITableView delegates


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 55;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	// The number of sections is based on the number of items in the data property list.
	return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	
	//return [arrayList count];	
    return end-start;
	
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{	
    CustomTableCell *cell = (CustomTableCell *)[tableView dequeueReusableCellWithIdentifier:@"CustomTableCell"];
	if(cell == nil) 
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomTableCell" owner:self options:nil];
        cell = (CustomTableCell *)[nib objectAtIndex:0];
        
        
        CAGradientLayer *gradient = [CAGradientLayer layer];
        gradient.frame = cell.bounds;
        
        CGColorRef topColor = [[UIColor whiteColor] CGColor];
        CGColorRef bottomColor = [[UIColor colorWithRed:0.80 green:.80 blue:.80 alpha:1.0] CGColor];
        gradient.colors = [NSArray arrayWithObjects:(id)topColor, (id)bottomColor, nil];
        
        [cell.layer insertSublayer:gradient atIndex:0];
    }
    
    //    cell.backgroundColor = COLORCELL
    
    arraySelect=[[NSMutableArray alloc]init];
    for(int i=start;i<end;i++)
    {
        [arraySelect addObject:[arrayList objectAtIndex:i]];
    }
    
	[cell settitle:[[arraySelect objectAtIndex:indexPath.row] objectForKey:FIELDNAME]];
    //cell.subtitle.text = stringTitle;
    cell.subtitle.text = [NSString stringWithFormat:@"%@",[[arraySelect objectAtIndex:indexPath.row] objectForKey:kDealBanner]];
    [cell setCostLabelstr:[NSString stringWithFormat:@"£%@",[[arraySelect objectAtIndex:indexPath.row] objectForKey:FIELDCOST]]];
    cell.description.text = [NSString stringWithFormat:@"%@",[[arraySelect objectAtIndex:indexPath.row] objectForKey:FIELDDESC]];
    
    [cell setDistanceLabelstr:[NSString stringWithFormat:@"%@",[ModalController  calDistancebetWithLat:[locationUser.strUserLat doubleValue] with:[locationUser.strUserLong doubleValue] with:[[[arraySelect objectAtIndex:indexPath.row ]objectForKey:@"Lat"]doubleValue] with:[[[arraySelect objectAtIndex:indexPath.row ]objectForKey:@"Long"]doubleValue]]]];
    
    [cell setDealLabelstr:[[arraySelect objectAtIndex:indexPath.row] objectForKey:FIELDDEAL]];
    cell.imagePro.placeholderImage=[UIImage imageNamed:@"placeholder.jpg"];
    cell.imagePro.imageURL =[NSURL URLWithString:[NSString stringWithFormat:@"http://acsdev.co.uk/AppServices/%@",[[[arraySelect objectAtIndex:indexPath.row]objectForKey:kVenueLogoImage] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    
    NSLog(@"%@",[NSString stringWithFormat:@"http://acsdev.co.uk/AppServices/%@",[[[arraySelect objectAtIndex:indexPath.row]objectForKey:kVenueLogoImage] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]);
    
    if([[arraySelect objectAtIndex:indexPath.row]objectForKey:@"DealIcon"])
    {
        cell.imageOfferDeal.image = [UIImage imageNamed:[NSString stringWithFormat:@"Offer Code %@.png",[[arraySelect objectAtIndex:indexPath.row]objectForKey:@"DealIcon"]]];
    }
    else   
    {
        [cell.imageOfferDeal  removeFromSuperview];
    }
    
    cell.dealUpdated.text = [[arraySelect  objectAtIndex:indexPath.row] objectForKey:@"DealUpdated"];
    
    //cell.venueImage.image = [(UIImageView*)[arrayImages objectAtIndex:indexPath.row] image];
    return (UITableViewCell *)cell;
	
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
    DetailsViewController *detailController = [[DetailsViewController    alloc] initWithNibName:@"DetailsViewController_Nw" bundle:nil];
    
    detailController.dictInfo = [[NSMutableDictionary alloc] initWithDictionary:[arraySelect objectAtIndex:indexPath.row]];
    detailController.isFromFav = 0;
    
    [self.navigationController pushViewController:detailController
                                         animated:YES];
    [detailController release];
}

#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource
{
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	_reloading = YES;
}

- (void)doneLoadingTableViewData
{	
	//  model should call this when its done loading
	_reloading = NO;
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:tableList];
	
}


#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
	[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	
	[_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
	
}


#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	
	[self reloadTableViewDataSource];
    
    [self  dataFromServer];
    //	[self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:3.0];
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view
{
	return _reloading; // should return if data source model is reloading
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}

////////Refreshing data code finish here

- (void)viewDidUnload
{
    NSLog(@"%s",__PRETTY_FUNCTION__);
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark- Manage SESSION
-(void)assignInitialValue
{
    start=0;
    if([arrayList count] > 10)
        end=10;
    else
        end = [arrayList count];
    
    if(start<10 && end<10)
    {
        [preBtn setEnabled:NO];
        [nxtBtn setEnabled:NO];
    }
    else if(end >= 10)
    {
        [preBtn setEnabled:NO];
        [nxtBtn setEnabled:YES];
    }
    
    [status setText:[NSString stringWithFormat:@"Results %d-%d of %d",start,end,[arrayList count]]];
    
}
-(void)manageSession:(BOOL)forPrevious
{
    if(forPrevious == NO)
    {
        for(int i=start;i<[arrayList count];i++)
        {
            if(i<(start+10))
                end++;
            else if(i == (start+10))
                break;
        }
    }
    else
    {
        int temp=start;
        for(int i=end;i>0;i--)
        {
            if(i>(end-10))
            {
                start--;
            }
            else if(i == (end-10))
            {
                end=temp;
                break;
            }
        }
    }
    if(start<10 && end<10)
    {
        [preBtn setEnabled:NO];
        [nxtBtn setEnabled:NO];
    }
    else if(end >= 10 && start<10)
    {
        [preBtn setEnabled:NO];
        [nxtBtn setEnabled:YES];
    }
    else if(end == [arrayList count])
    {
        [preBtn setEnabled:YES];
        [nxtBtn setEnabled:NO];
    }
    else
    {
        [preBtn setEnabled:YES];
        [nxtBtn setEnabled:YES];
    }
    [status setText:[NSString stringWithFormat:@"Results %d-%d of %d",start,end,[arrayList count]]];
    [tableList reloadData];
}
-(IBAction)clickToNext:(id)sender
{
    if(end < [arrayList count])
    {
        start=end;
        [self manageSession:NO];
    }
}
-(IBAction)clickToPre:(id)sender
{
    if(start>0)
        [self manageSession:YES];
}

@end
